package com.thunder.rebot.rebotclient.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.thunder.rebot.rebotclient.R;
import com.thunder.rebot.rebotclient.constant.Constants;
import com.thunder.rebot.rebotclient.entity.Network;
import com.thunder.rebot.rebotclient.entity.PicRegistEntity;
import com.thunder.rebot.rebotclient.entity.SocketConectState;
import com.thunder.rebot.rebotclient.entity.UserInformationEntity;
import com.thunder.rebot.rebotclient.service.ServiceClient;
import com.thunder.rebot.rebotclient.utils.ClientUtils;
import com.thunder.rebot.rebotclient.utils.LogUtil;
import com.thunder.rebot.rebotclient.utils.TRCommonUtil;
import com.thundersoft.sdk.FaceDetector;
import com.thundersoft.sdk.FaceInfo;
import com.thundersoft.sdk.FaceRecognizer;
import com.thundersoft.sdk.ImageData;
import com.thundersoft.sdk.Point;
import com.thundersoft.sdk.PointDetector;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by yuechunan on 18-7-2.
 */

public class RegisterActivity extends BaseActivity  {

    private static final String TAG = "RegisterActivity";
    @BindView(R.id.center_txt)
    public TextView centerTxt;
    @BindView(R.id.left_img)
    public ImageView leftImg;
    @BindView(R.id.right_txt)
    public TextView rightTxt;
    @BindView(R.id.display_img)
    public ImageView displayImg;
    @BindView(R.id.camera_btn)
    public Button cameraBtn;
    @BindView(R.id.select_btn)
    public Button selectBtn;
    @BindView(R.id.ok_upload)
    public Button uploadBtn;
    private File file;
    private Bitmap bitmap;
    private final String modelPath1 = "/sdcard/TSFaceDetector5.1.1.640x480.sta";
    private final String modelPath2 = "/sdcard/TSPointDetector5.0.pts5.dat";
    private final String modelPath3 = "/sdcard/TSFaceRecognizer5.0.RN50.49w.s4.ID.sta";
    private final String modelPath4 = "/sdcard/TSPoseEstimation1.1.0.ext.dat";

    private FaceDetector mFaceDetector;
    private PointDetector mPointDetector;
    private FaceRecognizer mFaceRecognizer;
    private String picName;
    private int maxLen = 40000;
    private String name;
    private byte[] sendByte;
    private int sendNum;
    private int cerrentNum;
    private Intent intent;
//    private UserInformationEntity uife;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        centerTxt.setText(R.string.register_title_txt);
        rightTxt.setText(R.string.history_register_txt);
//        uife = getUserinfor();
    }
    /*登录传递过来的用户信息
     */
    private UserInformationEntity getUserinfor(){
        intent = getIntent();
        Bundle bundle = intent.getExtras();
        return (UserInformationEntity)bundle.getSerializable("uerinfo");
    }
    @OnClick({R.id.left_img, R.id.right_txt, R.id.camera_btn, R.id.select_btn, R.id.ok_upload})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.left_img:
                finish();
                break;
            case R.id.right_txt:
                Intent intentMain = new Intent(this, DisplayFaceActivity.class);
                startActivity(intentMain);
                break;
            case R.id.camera_btn:
                //拍照
//                takePicture();
                useCamera();
                break;
            case R.id.select_btn:
                //选择照片
                selectPicture();
                break;
            case R.id.ok_upload:
                initRegister(bitmap);
                break;
        }
    }

    //识别
    private void initRegister(final Bitmap bitmap1) {
        //注册名字
        final EditText edtUser = new EditText(this);
        final EditText edtUserPw = new EditText(this);
        edtUser.setMaxLines(1);
        new AlertDialog.Builder(this)
                .setTitle("温馨提示")
                .setIcon(android.R.drawable.ic_dialog_info)
                .setView(edtUser)
//                .setView(edtUserPw)
//                .setMessage("用户名称:" +uife.getName() )
                .setCancelable(false)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                        name = edtUser.getText().toString();
//                        name = uife.getName();
                        //压缩图片,防止传输的时候过大
                        bitmap=TRCommonUtil.compressImage(bitmap1,0.8f);
                        sendByte = TRCommonUtil.bitmapToBytes(bitmap);
                        LogUtil.i(TAG,"注册图片的大小后=="+sendByte.length);
                        if (ClientUtils.connectFlag) {
                            new Thread("send") {
                                @Override
                                public void run() {
                                    cerrentNum=0;
//                                    sendByte = TRCommonUtil.bitmapToBytes(bitmap);
                                    sendNum = (int) Math.ceil(sendByte.length / maxLen) + 1;
//                                    LogUtil.d(TAG, "注册照片 : 客户端发送的  sendbyte[]==" + sendByte.length + ",," + Arrays.toString(sendByte));
                                    sendPictureData(0);
//                                    if (sendByte.length >= maxLen) {
//                                        int sendNum = (int) Math.ceil(sendByte.length / maxLen) + 1;
//                                        LogUtil.d(TAG, "注册照片 : 客户端发送的  sendNum==" + sendNum + "是否取余==" + sendByte.length % 10000);
//                                        for (int i = 0; i < sendNum; i++) {
//                                            if (sendByte.length % maxLen == 0) {
//                                                int sendLen = maxLen;
//                                                sendPictureData(sendLen, 0, name, sendByte, sendNum,i);
//                                            } else {
//                                                LogUtil.d(TAG, "注册照片 i==" + i+",,sendNum=="+sendNum);
//                                                if (i == sendNum - 1) {
//                                                    int sendLen = sendByte.length - maxLen * (sendNum - 1);
//                                                    LogUtil.d(TAG, "注册照片 : 客户端发送的  有余数，最后一次发的长度 sendLen==" + sendLen);
//                                                    sendPictureData(sendLen, 1, name, sendByte, sendNum,i);
//                                                } else {
//                                                    int sendLen = maxLen;
//                                                    sendPictureData(sendLen, 0, name, sendByte, sendNum,i);
//                                                }
//                                            }
//                                            try {
//                                                Thread.sleep(100);
//                                            } catch (InterruptedException e) {
//                                                e.printStackTrace();
//                                            }
//                                        }
//                                    } else {
//                                        LogUtil.d(TAG, "注册照片 : 客户端发送的  sendbyte[]一次发完");
//                                        sendPictureData(sendByte.length, 3, name, sendByte, 1,0);
//                                    }
                                }
                            }.start();
                        } else {
                            Toast.makeText(RegisterActivity.this, "没有连接服务端，请连接", Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .show();
    }

    /*
     * @param sendLen  最后一次发送的长度
     * @param i        发送的类型 0-整数倍发送 1-有余数的发送 2-一次发完
     * @param name     照片注册的姓名
     * @param sendByte 照片注册的byte[]数组
     * @param sendNum  照片的byte[]数组发送的次数
     */
    private void sendPictureData(int cerrentNum0) {
        int i;
        int sendLen=0;
        cerrentNum=cerrentNum0;
        if (sendByte.length >= maxLen) {
            if (sendByte.length % maxLen == 0) {
                sendLen = maxLen;
                i=0;
            } else {
                if (cerrentNum == sendNum - 1) {
                    sendLen = sendByte.length - maxLen * (sendNum - 1);
                    i=1;
                } else {
                    sendLen = maxLen;
                    i=0;
                }
            }
        }else{
            i=2;
        }
        if (i == 0) {
            byte[] data3 = new byte[maxLen];
            Network.SomeRequest request = new Network.SomeRequest();
            request.sendType = 1;
            request.name = name;
            System.arraycopy(sendByte, maxLen * cerrentNum, data3, 0, maxLen);
            request.picBit = data3;
            request.picBitLen=sendByte.length;
            request.sendNum=sendNum;
            request.cerrentNum=cerrentNum;
            LogUtil.d(TAG, "注册照片 单次发送的byte=="+Arrays.toString(data3));
            ServiceClient.client.sendTCP(request);
        } else if (i == 1) {
            byte[] data3 = new byte[sendLen];
            Network.SomeRequest request = new Network.SomeRequest();
            request.sendType = 1;
            request.name = name;
            System.arraycopy(sendByte, maxLen * (sendNum - 1), data3, 0, sendLen);
            request.picBit = data3;
            request.picBitLen=sendByte.length;
            request.sendNum=sendNum;
            request.cerrentNum=cerrentNum;
            LogUtil.d(TAG, "注册照片 最后一次次发送的byte=="+Arrays.toString(data3));
            ServiceClient.client.sendTCP(request);
        } else if (i == 2) {
            Network.SomeRequest request = new Network.SomeRequest();
            request.sendType = 1;
            request.name = name;
            request.picBit = sendByte;
            request.picBitLen=sendByte.length;
            request.sendNum=sendNum;
            request.cerrentNum=cerrentNum;
            ServiceClient.client.sendTCP(request);
        }
        cerrentNum++;
        LogUtil.d(TAG, "注册照片 : 客户端发送成功");
    }

    private void selectPicture() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, TRCommonUtil.PHOTO_REQUEST_GALLERY);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TRCommonUtil.PHOTO_REQUEST_TAKEPHOTO && resultCode == RESULT_OK) {
//            bitmap=TRCommonUtil.getBitmapFromUri(RegisterActivity.this, Uri.fromFile(file));
            //上面的方法的是原始大小的bitmap，当图库选择的图片很大时程序极有可能会报OOM。为了避免
            //OOM咱们需要改进该方法，在 BitmapFactory.decodeStream 之前压缩图片
            try {
                bitmap = TRCommonUtil.getBitmapFormUri(RegisterActivity.this, Uri.fromFile(file));
            } catch (IOException e) {
                e.printStackTrace();
            }

            LogUtil.i(TAG, "注册前 file大小==" + file.length());
//            displayImg.setImageURI(Uri.fromFile(file));
            displayImg.setImageBitmap(bitmap);
            //在手机相册中显示刚拍摄的图片
            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri contentUri = Uri.fromFile(file);
            mediaScanIntent.setData(contentUri);
            sendBroadcast(mediaScanIntent);
        } else if (requestCode == TRCommonUtil.PHOTO_REQUEST_GALLERY && resultCode == RESULT_OK) {
            if (data != null) {
                if (data.getData() != null) {
                    bitmap = TRCommonUtil.getBitmapFromUri(RegisterActivity.this, data.getData());
                    displayImg.setImageBitmap(bitmap);
                }
            }
        }
    }
    @Override
    public void conectState(int code,final String description) {
        switch (code) {
            case 1:
                Gson gson = new Gson();
                final SocketConectState socketConectState = gson.fromJson(description, new TypeToken<SocketConectState>() {
                }.getType());

                switch (Integer.valueOf(socketConectState.getCode())) {
                    case 10://连接成功
                        ClientUtils.robotConnectFlag = true;
                        break;
                    case 9://连接断开
                        ClientUtils.robotConnectFlag = false;

                        break;
                    case 8://未连接成功
                        ClientUtils.robotConnectFlag = false;
                        break;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(RegisterActivity.this, socketConectState.getDescription(), Toast.LENGTH_SHORT).show();
                    }
                });

                break;
        }
    }
    /**
     * 使用相机
     */
    private void useCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        TRCommonUtil.caremaPath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/test/" + System.currentTimeMillis() + ".jpg";
        file = new File(TRCommonUtil.caremaPath);
        file.getParentFile().mkdirs();
        //改变Uri  com.xykj.customview.fileprovider注意和xml中的一致
        Uri uri = FileProvider.getUriForFile(this, "com.thunder.robot.thunderrobot.fileprovider", file);
        //添加权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, TRCommonUtil.PHOTO_REQUEST_TAKEPHOTO);
    }

    @Override
    public void getRebackType(Object value) {
        LogUtil.i(TAG,"getRebackType value=="+value);
        if(value instanceof PicRegistEntity){
            switch(((PicRegistEntity) value).getCode()){
                            case 0:
                //小车的方向的回调
                break;
            case 1:
                //照片注册的回调
                if (ClientUtils.connectFlag) {
                    new Thread("send") {
                        @Override
                        public void run() {
                            LogUtil.i(TAG, "getRebackType  cerrentNum==" + cerrentNum + "sendNum==" + sendNum);
                            if (cerrentNum < sendNum) {
                                sendPictureData(cerrentNum);
                            }else{
                                //上传图片全部完成，需要提示，注册成功；
//                                runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        Toast.makeText(RegisterActivity.this, "注册成功，请登录", Toast.LENGTH_SHORT).show();
//                                        }
//                                });
                                //返回给loginactivity 登录
//                                setResult(Constants.REQUESTCODE);
                            }
                        }
                    }.start();
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(RegisterActivity.this, "没有连接服务端，请连接", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                break;
                case 5:
                    if (((PicRegistEntity) value).isRigst()){//成功注册
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(RegisterActivity.this,"注册成功",Toast.LENGTH_SHORT).show();
                            }
                        });
                        //返回给loginactivity 登录
                        setResult(Constants.REQUESTCODE);
                        RegisterActivity.this.finish();
                    }else{//注册失败，请重新拍照注册
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(RegisterActivity.this,"注册失败，请重新注册",Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                    break;
            }
        }
//        switch (value) {
//            case 0:
//                //小车的方向的回调
//                break;
//            case 1:
//                //照片注册的回调
//                if (ClientUtils.connectFlag) {
//                    new Thread("send") {
//                        @Override
//                        public void run() {
//                            LogUtil.i(TAG, "getRebackType  cerrentNum==" + cerrentNum + "sendNum==" + sendNum);
//                            if (cerrentNum < sendNum) {
//                                sendPictureData(cerrentNum);
//                            }else{
//                                //上传图片全部完成，需要提示，注册成功；
//                                runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        Toast.makeText(RegisterActivity.this, "注册成功，请登录", Toast.LENGTH_SHORT).show();
//                                        }
//                                });
//                                //返回给loginactivity 登录
//                                setResult(Constants.REQUESTCODE);
//                            }
//                        }
//                    }.start();
//                } else {
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            Toast.makeText(RegisterActivity.this, "没有连接服务端，请连接", Toast.LENGTH_SHORT).show();
//                        }
//                    });
//                }
//                break;
//        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtil.i(TAG,"@@@@onResume");
        ServiceClient.setOnPackageRemoveListener(RegisterActivity.this);
    }
}

